package cn.schoolwow.quickapi.config;

import cn.schoolwow.ams.domain.block.router.RouterBlockBuilder;
import cn.schoolwow.ams.domain.option.QuickAMSListener;
import cn.schoolwow.ams.domain.option.QuickAMSOption;
import cn.schoolwow.quickapi.domain.QuickAPIOption;
import cn.schoolwow.quickapi.module.ams.api.aware.APIClazzListBlockAware;
import cn.schoolwow.quickapi.module.common.domain.APIDocument;
import cn.schoolwow.quickapi.module.initial.flow.CheckQuickAPIOptionFlow;
import cn.schoolwow.quickapi.module.initial.service.InitialQuickAPICompositeBusiness;
import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickflow.QuickFlow;
import cn.schoolwow.quickflow.QuickFlowBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Configuration
@ComponentScan(basePackages = "cn.schoolwow.quickapi")
public class QuickAPIConfig {
    @Bean
    public QuickFlow quickAPIFlow(QuickAMSOption quickAMSOption, QuickAPIOption quickAPIOption){
        APIDocument apiDocument = new APIDocument();
        QuickFlow quickAPIFlow = QuickFlowBuilder.newInstance()
                .putContextTemporaryInstanceData(quickAMSOption)
                .putContextTemporaryInstanceData(quickAPIOption)
                .putContextTemporaryInstanceData(apiDocument);
        //异步加载API接口
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.execute(()->{
            try {
                quickAPIFlow.startFlow(new CheckQuickAPIOptionFlow())
                        .next(new InitialQuickAPICompositeBusiness())
                        .execute();
            }catch (Exception e){
                e.printStackTrace();
            }
        });
        return quickAPIFlow;
    }

    @Bean
    @Autowired
    public QuickAMSListener quickAPIQuickAMSListener(ApplicationContext applicationContext){
        QuickAMSListener quickAMSListener = new QuickAMSListener() {
            @Override
            public void addRouterBlockArray(RouterBlockBuilder routerBlockBuilder) {
                routerBlockBuilder.children("/api", "接口文档")
                        .block(applicationContext.getBean(APIClazzListBlockAware.class));
//                        .block(applicationContext.getBean(ExecuteAPIAware.class));
            }

            @Override
            public DAO getDAO(String daoName) {
                return null;
            }
        };
        return quickAMSListener;
    }
}